package com.wodan.zhongjinjicang.common.orm.command.write;

import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.Callable;

import com.wodan.zhongjinjicang.common.orm.RdsCommonWriteDao;
import com.wodan.zhongjinjicang.common.orm.command.base.AbstractSqlCommandExecutor;
import com.wodan.zhongjinjicang.common.orm.metadata.MethodMetaData;
import com.wodan.zhongjinjicang.common.orm.metadata.TableFieldMetaData;
import com.wodan.zhongjinjicang.common.orm.metadata.TableMetaData;
import com.wodan.zhongjinjicang.common.orm.utils.ReflectionUtils;
import com.wodan.zhongjinjicang.common.orm.utils.SqlGenernateUtils;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.util.Assert;

import com.google.common.collect.Lists;


/**
 * 插入操作的执行者
 * 
 * @ClassName: SqlInsertExecutor
 * @author Administrator
 * @date 2015-11-5 下午4:43:12
 * @history
 * 
 */
public class SqlBatchDeleteExecutor extends AbstractSqlCommandExecutor {
	
	@Override
	protected Object doExecute(final TableMetaData tableMetaData, MethodMetaData methodMetaData,
							   final Object[] args) {
		Assert.notEmpty(args);
		Assert.isTrue(args.length == 1);

		final List<?> entityList = (List<?>) args[0];

		// 解析表名
		final String tableName = tableMetaData.getTableName();

		// 只支持根据主键id删除
		TableFieldMetaData idField = tableMetaData.getIdField();
		final String[] columnNames = new String[] { idField.getColumnName().toString() };

		// 生成sql语句插入数据库
		final String deleteSql = super.createCachedSqlScript(new Callable<String>() {
			@Override
			public String call() throws Exception {
				return SqlGenernateUtils.createDeleteSql(tableName, columnNames);
			}
		}, tableName, columnNames);

		// 生成value字段
		List<Object[]> valuesList = Lists.newArrayListWithCapacity(entityList.size());
		for (Object entity : entityList) {
			Object idValue = idField.readFieldValue(entity);
			if (idValue == null) {
				throw new IllegalArgumentException("主键id的值为空");
			}
			final Object[] values = new Object[] { idValue };
			valuesList.add(values);
		}
		
		return jdbcTemplate.batchUpdate(deleteSql, valuesList);
	}

	@Override
	public Method getProxyMethod() {
		return ReflectionUtils.findMethod(RdsCommonWriteDao.class, "batchDelete", List.class);
	}

	@Override
	public SqlCommandType getSqlCommandType() {
		return SqlCommandType.DELETE;
	}
}
